package com.shop.mms_client.ui;

import android.app.Dialog;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.EditText;
import android.widget.RadioGroup;
import androidx.appcompat.app.AlertDialog;
import androidx.fragment.app.DialogFragment;
import androidx.lifecycle.ViewModelProvider;
import com.shop.mms_client.R;
import com.shop.mms_client.model.BlacklistItem;
import com.shop.mms_client.viewmodel.BlacklistViewModel;
import com.shop.mms_client.utils.ErrorHandler;

public class AddBlacklistDialog extends DialogFragment {
    
    @Override
    public Dialog onCreateDialog(Bundle savedInstanceState) {
        AlertDialog.Builder builder = new AlertDialog.Builder(requireActivity());
        View view = LayoutInflater.from(getContext()).inflate(R.layout.dialog_add_blacklist, null);
        
        EditText valueEdit = view.findViewById(R.id.valueEdit);
        RadioGroup typeGroup = view.findViewById(R.id.typeGroup);
        
        builder.setView(view)
            .setTitle("添加黑名单")
            .setPositiveButton("添加", (dialog, which) -> {
                String value = valueEdit.getText().toString().trim();
                if (value.isEmpty()) {
                    ErrorHandler.showError(valueEdit, "请输入内容");
                    return;
                }
                
                String type = typeGroup.getCheckedRadioButtonId() == R.id.phoneRadio ? 
                    "PHONE" : "KEYWORD";
                    
                if (type.equals("PHONE") && !isValidPhoneNumber(value)) {
                    ErrorHandler.showError(valueEdit, "请输入有效的电话号码");
                    return;
                }
                
                BlacklistViewModel viewModel = new ViewModelProvider(requireParentFragment())
                    .get(BlacklistViewModel.class);
                viewModel.addBlacklistItem(new BlacklistItem(value, type));
            })
            .setNegativeButton("取消", null);
            
        return builder.create();
    }

    private boolean isValidPhoneNumber(String phone) {
        return phone.matches("^1[3-9]\\d{9}$");
    }
} 